package com.chrray.position.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @anthor ch
 * @description 请求日志
 * @date
 */
@Aspect
@Component
@Slf4j
public class ControllerMethodExecutionLogAspect {

    private static final String START_TIME = "requestStartTime";

    @Pointcut("execution(public * com.chrray.position.controller..*.*(..))")
    public void log() {

    }

    @Before("log()")
    public void doStart(JoinPoint joinpoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest req = attributes.getRequest();

        long start = System.currentTimeMillis();
        req.setAttribute(START_TIME, start);

        log.info("=========================================== 开始请求 ===========================================");
        log.info("********request start,url = {}",req.getRequestURL().toString());
        log.info("请求方式 = {}",req.getMethod());
        log.info("客户端IP = {}",req.getRemoteAddr());
        log.info("请求方法 = {}",joinpoint.getSignature().getDeclaringTypeName()+"."+joinpoint.getSignature().getName());


    }

    @AfterReturning(returning = "object",pointcut="log()")
    public void doEnd(Object object) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest req = attributes.getRequest();
        long start = (Long) req.getAttribute(START_TIME);
        long end = System.currentTimeMillis();
        log.info("总耗时{}", end - start+"毫秒");
        log.info("=========================================== 请求结束 ===========================================");
    }

}
